package mww.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mww.common.DaoException;
import mww.common.Page;
import mww.common.ServiceException;
import mww.javabean.entity.*;
import mww.javabean.service.*;

public class TeacherCServlet extends HttpServlet {
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpServletRequest req = (HttpServletRequest) request;// 将request强制转换为HttpServletRequest类型
		HttpServletResponse res = (HttpServletResponse) response;// 将response强制转换为HttpServletResponse类型
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		String action = request.getParameter("action");
		if (action.equals("list")) {
			doList(request, response);
		} else if (action.equals("show")) {
			doShow(request, response);
		} else if (action.equals("delete")) {
			doDelete(request, response);
		} else if (action.equals("add")) {
			doAdd(request, response);
		} else if (action.equals("listCourse")) {
			doListCourse(request, response);
		} else if (action.equals("checkCourse")) {
			doCheckCourse(request, response);
		} else if (action.equals("changePwd")) {
			doChangePwd(request, response);
		} else if (action.equals("checkTeacher")) {
			doCheckTeacher(request, response);
		} else if (action.equals("showTeacher")) {
			doShowTeacher(request, response);
		} else if (action.equals("checkGrade")) {
			doCheckGrade(request, response);
		} else if (action.equals("showGrade")) {
			doShowGrade(request, response);
		} else if (action.equals("saveGrade")) {
			doSaveGrade(request, response);
		} else {
			HttpSession session = request.getSession();
			session.setAttribute("message", "异常访问，请登录！");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}

	}

	public void doList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息

		TeacherCService service = new TeacherCServiceImpl();
		User user = (User) session.getAttribute("user");// 从session中取出user对象
		int curPage = 1;
		String temp = request.getParameter("curPage");
		if (temp != null) {
			curPage = Integer.parseInt(request.getParameter("curPage"));
		}
		try {
			Map map = service.findTeacherCByTeacherNo(user.getLoginName(), 0, curPage);
			ArrayList list = (ArrayList) map.get("list");
			Page pa = (Page) map.get("pa");
			request.setAttribute("curPage", pa.getCurPage());// 向显示页传递当前页页码
			request.setAttribute("pageCount", pa.getPageCount());// 向显示页传递总页数
			request.setAttribute("list", list);// 向显示页传递结果集
			request.getRequestDispatcher("/teacher/teacherCList.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	public void doDelete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		TeacherCService service = new TeacherCServiceImpl();
		StudentCService scservice = new StudentCServiceImpl();
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		String teacherNo = request.getParameter("teacherNo");
		String courseNo = request.getParameter("courseNo");
		Integer tcTeacherNo = Integer.parseInt(request.getParameter("tcTeacherNo"));

		int curPage = 1;
		String temp = request.getParameter("curPage");
		if (temp != null) {
			curPage = Integer.parseInt(request.getParameter("curPage"));
		}
		try {
			if (scservice.checkStudentCExistById(teacherNo, courseNo, tcTeacherNo)) {
				session.setAttribute("message", "删除记录存在关联项，禁止删除！");
				request.getRequestDispatcher("/teacher/tcServlet?action=list").forward(request, response);
			} else {

				service.delTeacherC(teacherNo, courseNo, tcTeacherNo);
				session.setAttribute("message", "删除教师信息成功！");
				request.getRequestDispatcher("/teacher/tcServlet?action=list").forward(request, response);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	public void doShow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		TeacherCService service = new TeacherCServiceImpl();

		Integer tcTeacherNo = Integer.parseInt(request.getParameter("tcTeacherNo"));
		String teacherNo = request.getParameter("teacherNo");
		String courseNo = request.getParameter("courseNo");
		try {
			TeacherC teacherC = new TeacherC();
			teacherC = service.findTeacherCById(teacherNo, courseNo, tcTeacherNo);
			request.setAttribute("tcTime1", teacherC.getTcTime().charAt(0)); // 提取天参数
																				// （时间组合：天-节）
			request.setAttribute("tcTime2", teacherC.getTcTime().charAt(2)); // 提取节次参数
																				// （时间组合：天-节）
			request.setAttribute("teacherC", teacherC);
			request.getRequestDispatcher("/teacher/teacherCShow.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	public void doAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		User user = (User) session.getAttribute("user");// 从session中取出user对象

		TeacherCService service = new TeacherCServiceImpl();
		CourseService cservice = new CourseServiceImpl();

		String teacherNo = user.getLoginName();
		String teacherName = user.getName();
		String courseNo = request.getParameter("courseNo");
		Integer tcTeacherNo = new Integer(request.getParameter("tcTeacherNo"));
		String tcLocation = request.getParameter("tcLocation");
		Integer tcCapacity = new Integer(request.getParameter("tcCapacity"));
		String tcTime1 = request.getParameter("tcTime1");
		String tcTime2 = request.getParameter("tcTime2");
		String tcTime = tcTime1 + "-" + tcTime2;// 上课时间组合为(天-节次)
		try {
			Course course = cservice.findCourseByCourseNo(courseNo);
			if (null == course) { // 课序号不存在
				session.setAttribute("message", "所要添加的课程不存在！");
				request.getRequestDispatcher("/teacher/teacherCAdd.jsp").forward(request, response);
			}
			// 检测数据库中是否存在相同课程
			else if (service.checkExistConflict(teacherNo, courseNo, tcTeacherNo)) {
				session.setAttribute("message", "所添任课已存在!");
				request.getRequestDispatcher("/teacher/teacherCAdd.jsp").forward(request, response);
			} else if (service.checkTimeConflict(teacherNo, tcTime)) {
				session.setAttribute("message", "新添时间与已有任课时间冲突!");
				request.getRequestDispatcher("/teacher/teacherCAdd.jsp").forward(request, response);
			} else {
				TeacherC tc = new TeacherC();
				tc.setTeacherNo(teacherNo);
				tc.setTeacherName(teacherName);
				tc.setCourseNo(course.getCourseNo()); // 从课程类中获取编号
				tc.setCourseName(course.getCourseName()); // 从课程类中获取课程名
				tc.setCredit(course.getCredit()); // 从课程类中获取学分
				tc.setTcTeacherNo(tcTeacherNo);
				tc.setTcLocation(tcLocation);
				tc.setTcTime(tcTime);
				tc.setTcCapacity(tcCapacity);
				service.addTeacherC(tc);
				session.setAttribute("message", "任课信息添加成功！");
				request.getRequestDispatcher("/teacher/tcServlet?action=list").forward(request, response);

			}
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	public void doCheckCourse(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		CourseService service = new CourseServiceImpl();
		String courseNo = request.getParameter("courseNo");
		String courseName = request.getParameter("courseName");
		Integer studyTime = null;
		if (request.getParameter("studyTime") != null && !request.getParameter("studyTime").equals(""))
			studyTime = new Integer(request.getParameter("studyTime"));
		Float credit = null;
		if (request.getParameter("credit") != null && !request.getParameter("credit").equals(""))
			credit = new Float(request.getParameter("credit"));
		Integer courseType = null;
		if (request.getParameter("courseType") != null && !request.getParameter("courseType").equals(""))
			courseType = new Integer(request.getParameter("courseType"));
		Integer term = null;
		if (request.getParameter("term") != null && !request.getParameter("term").equals(""))
			term = new Integer(request.getParameter("term"));

		request.setAttribute("courseNo", courseNo);
		request.setAttribute("courseName", courseName);
		request.setAttribute("studyTime", studyTime);
		request.setAttribute("credit", credit);
		request.setAttribute("courseType", courseType);
		request.setAttribute("term", term);

		Course course = new Course(courseNo, courseName, studyTime, credit, courseType, term);
		int curPage = 1;
		String temp = request.getParameter("curPage");
		if (temp != null) {
			curPage = Integer.parseInt(request.getParameter("curPage"));
		}
		try {
			Map map = service.findAllCourseByMostCon(course, curPage);
			ArrayList list = (ArrayList) map.get("list");
			Page pa = (Page) map.get("pa");
			request.setAttribute("curPage", pa.getCurPage());// 向显示页传递当前页页码
			request.setAttribute("pageCount", pa.getPageCount());// 向显示页传递总页数
			request.setAttribute("list", list);// 向显示页传递结果集
			request.getRequestDispatcher("/teacher/courseFind.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	public void doListCourse(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		CourseService service = new CourseServiceImpl();
		int curPage = 1;
		String temp = request.getParameter("curPage");
		if (temp != null) {
			curPage = Integer.parseInt(request.getParameter("curPage"));
		}
		try {
			Map map = service.findAllCourse(curPage);
			ArrayList list = (ArrayList) map.get("list");
			Page pa = (Page) map.get("pa");
			request.setAttribute("curPage", pa.getCurPage());// 向显示页传递当前页页码
			request.setAttribute("pageCount", pa.getPageCount());// 向显示页传递总页数
			request.setAttribute("list", list);// 向显示页传递结果集
			request.getRequestDispatcher("/teacher/courseFind.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	private void doChangePwd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		TeacherService teService = new TeacherServiceImpl();
		String loginName = ((User) session.getAttribute("user")).getLoginName();
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword1");
		try {
			Teacher teacher = teService.findTeacherByTeacherNo(loginName);
			if (!teacher.getPassword().equals(oldPassword)) { // 若输入密码不吻合
				session.setAttribute("message", "原密码与账号不匹配");
			} else if (teacher.getPassword().equals(newPassword)) { // 若密码与账号吻合，则更改密码
				session.setAttribute("message", "原密码与新密码不能相同");
				request.getRequestDispatcher("/teacher/changePwd.jsp").forward(request, response);
			} else {
				teService.updatePwd(loginName, newPassword);
				session.setAttribute("message", "修改成功");
				request.getRequestDispatcher("/teacher/changePwd.jsp").forward(request, response);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	public void doCheckTeacher(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		TeacherService teService = new TeacherServiceImpl();
		String teacherNo = request.getParameter("teacherNo");
		String teacherName = request.getParameter("teacherName");
		Integer professional = null;
		if (request.getParameter("professional") != null && !request.getParameter("professional").equals("")) {
			professional = new Integer(request.getParameter("professional"));
		}
		String phone = request.getParameter("phone");
		String subject = request.getParameter("subject");
		request.setAttribute("teacherNo", teacherNo);
		request.setAttribute("teacherName", teacherName);
		request.setAttribute("professional", professional);
		request.setAttribute("phone", phone);
		request.setAttribute("subject", subject);
		int curPage = 1;
		String temp = request.getParameter("curPage");
		if (temp != null) {
			curPage = Integer.parseInt(request.getParameter("curPage"));
		}
		try {
			// 查询条件封装进Teacher类
			Teacher condition = new Teacher();
			condition.setTeacherNo(teacherNo);
			condition.setTeacherName(teacherName);
			condition.setProfessional(professional);
			condition.setPhone(phone);
			condition.setSubject(subject);
			Map map = teService.findAllTeacherByMostCon(condition, curPage);
			ArrayList list = (ArrayList) map.get("list");
			Page pa = (Page) map.get("pa");
			request.setAttribute("curPage", pa.getCurPage());// 向显示页传递当前页页码
			request.setAttribute("pageCount", pa.getPageCount());// 向显示页传递总页数
			request.setAttribute("list", list);// 向显示页传递结果集
			request.getRequestDispatcher("/teacher/teacherCheck.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	public void doShowTeacher(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		User user = (User) session.getAttribute("user");
		TeacherService teservice = new TeacherServiceImpl();
		try {
			Teacher teacher = teservice.findTeacherByTeacherNo(user.getLoginName());
			request.setAttribute("teacher", teacher);
			request.getRequestDispatcher("/teacher/teacherShow.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	public void doCheckGrade(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		User user = (User) session.getAttribute("user");// 从session中取出user对象
		TeacherCService service = new TeacherCServiceImpl();
		int curPage = 1;
		String temp = request.getParameter("curPage");
		if (temp != null) {
			curPage = Integer.parseInt(request.getParameter("curPage"));
		}
		try {
			Map map = service.findTeacherCByTeacherNo(user.getLoginName(), 0, curPage);
			ArrayList list = (ArrayList) map.get("list");
			Page pa = (Page) map.get("pa");
			request.setAttribute("curPage", pa.getCurPage());// 向显示页传递当前页页码
			request.setAttribute("pageCount", pa.getPageCount());// 向显示页传递总页数
			request.setAttribute("list", list);// 向显示页传递结果集
			request.getRequestDispatcher("/teacher/checkGrade.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	public void doShowGrade(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String courseNo = request.getParameter("courseNo");
		String teacherNo = request.getParameter("teacherNo");
		Integer tcTeacherNo = Integer.parseInt(request.getParameter("tcTeacherNo"));
		request.setAttribute("teacherNo", teacherNo);
		request.setAttribute("courseNo", courseNo);
		request.setAttribute("tcTeacherNo", tcTeacherNo);

		try {
			StudentCService scService = new StudentCServiceImpl();
			ArrayList list = new ArrayList();
			list = (ArrayList) scService.findAllStudentById(teacherNo, courseNo, tcTeacherNo);
			request.setAttribute("list", list);
			request.getRequestDispatcher("/teacher/submitGrade.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	public void doSaveGrade(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		TeacherCService tcService = new TeacherCServiceImpl();

		String studentNos = request.getParameter("studentNos");// 获得提交成绩的记录学号拼接字符串
		String usualScores = request.getParameter("usualScores");// 获得提交成绩的平时成绩拼接字符串
		String lastScores = request.getParameter("lastScores");// 获得提交的期末成绩拼接字符串
		String courseNo = request.getParameter("courseNo");
		String teacherNo = request.getParameter("teacherNo");
		Integer tcTeacherNo = Integer.parseInt(request.getParameter("tcTeacherNo"));
		Integer type = Integer.parseInt(request.getParameter("type"));// 获得提交类型 暂时或永久

		request.setAttribute("teacherNo", teacherNo);
		request.setAttribute("courseNo", courseNo);
		request.setAttribute("tcTeacherNo", tcTeacherNo);

		try {
			// 利用StringTokenizer和"'"将拼接字符串进行分割
			StringTokenizer st1 = new StringTokenizer(studentNos, ",");
			StringTokenizer st2 = new StringTokenizer(usualScores, ",");
			StringTokenizer st3 = new StringTokenizer(lastScores, ",");
			String studentNo = null;
			Float usualScore = null;
			Float lastScore = null;
			// 通过循环来保存提交的成绩集合
			StudentCService studentService = new StudentCServiceImpl();
			while (st1.hasMoreTokens() && st2.hasMoreTokens() && st3.hasMoreTokens()) {
				studentNo = st1.nextToken();
				usualScore = Float.parseFloat(st2.nextToken());
				lastScore = Float.parseFloat(st3.nextToken());
				studentService.updateScore(studentNo, teacherNo, courseNo, tcTeacherNo, usualScore, lastScore, type);
			}
			if (type==1) {	//永久提交成绩才更新任课信息中的平均分、最低分、最高分
				Score score = studentService.findMaxMinAvg(teacherNo, courseNo, tcTeacherNo);
				tcService.updateScoreInTeacherC(teacherNo, courseNo, tcTeacherNo, score.getMaxScore(),
						score.getMinScore(), score.getAvgScore());
				session.setAttribute("message", "学生成绩永久提交成功！");
			} else {
				session.setAttribute("message", "学生成绩暂时提交成功！");
			}

			// 查询显示修改后的学生成绩
			StudentCService scService = new StudentCServiceImpl();
			ArrayList list = new ArrayList();
			list = (ArrayList) scService.findAllStudentById(teacherNo, courseNo, tcTeacherNo);
			request.setAttribute("list", list);
			request.getRequestDispatcher("/teacher/submitGrade.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}
}
